import React, { useState, useEffect, useCallback, useMemo } from 'react'

// 图片缓存管理
const imageCache = new Map<string, HTMLImageElement>()
const sliceCache = new Map<string, string>()

// 新的参数格式 - 通过图片ID和行列切分显示
interface NewImageSliceViewerProps {
  imageSliceId: string // 图片切片ID，格式为 "imageId_row_col"
  baseUrl?: string // 基础URL，默认为 '/api/g/f/p/'
  alt?: string
  className?: string
  width?: number
  height?: number
  onLoad?: () => void
  onError?: () => void
}

// URL参数格式 - 通过URL参数定位切片
interface UrlParamImageSliceViewerProps {
  imageId: string // 图片ID
  row: number // 行位置
  col: number // 列位置
  baseUrl?: string // 基础URL，默认为 '/api/g/f/p/'
  alt?: string
  className?: string
  width?: number
  height?: number
  onLoad?: () => void
  onError?: () => void
}

// 传统的props支持（向后兼容）
interface LegacyImageSliceViewerProps {
  imageUrl: string
  position: {
    row: number
    col: number
  }
  alt?: string
  className?: string
  width?: number
  height?: number
  onLoad?: () => void
  onError?: () => void
}

// 组合props类型
type ImageSliceViewerProps =
  | NewImageSliceViewerProps
  | UrlParamImageSliceViewerProps
  | LegacyImageSliceViewerProps

const ImageSliceViewer = React.memo(function ImageSliceViewer(
  props: ImageSliceViewerProps
) {
  // 统一处理参数
  const {
    alt = '图片',
    className = '',
    width = 28,
    height = 28,
    onLoad,
    onError
  } = props

  // 获取标准化参数 - 使用useMemo来避免每次渲染都重新创建对象
  const imageSliceId = 'imageSliceId' in props ? props.imageSliceId : undefined
  const imageSliceIdBaseUrl =
    'imageSliceId' in props ? props.baseUrl : undefined
  const imageId = 'imageId' in props ? props.imageId : undefined
  const imageIdBaseUrl = 'imageId' in props ? props.baseUrl : undefined
  const row = 'row' in props ? props.row : undefined
  const col = 'col' in props ? props.col : undefined
  const imageUrl = 'imageUrl' in props ? props.imageUrl : undefined
  const positionRow = 'position' in props ? props.position.row : undefined
  const positionCol = 'position' in props ? props.position.col : undefined

  const params = useMemo(() => {
    if (imageSliceId) {
      // 新格式：使用图片切片ID（格式为 "imageId_row_col"）
      const parts = imageSliceId.split('_')
      if (parts.length !== 3) {
        // 格式不符合时，返回直接显示原始图片的标记
        return {
          imageId: 'fallback',
          row: 0,
          col: 0,
          baseUrl: '',
          fullUrl: imageSliceId, // 直接使用原始值作为图片URL
          cacheKey: imageSliceId,
          useFallback: true
        }
      }

      const parsedImageId = parts[0]
      const parsedRow = parseInt(parts[1], 10)
      const parsedCol = parseInt(parts[2], 10)

      if (isNaN(parsedRow) || isNaN(parsedCol)) {
        // 格式不符合时，返回直接显示原始图片的标记
        return {
          imageId: 'fallback',
          row: 0,
          col: 0,
          baseUrl: '',
          fullUrl: imageSliceId, // 直接使用原始值作为图片URL
          cacheKey: imageSliceId,
          useFallback: true
        }
      }

      const fullUrl = `${imageSliceIdBaseUrl || '/api/g/f/p/'}${parsedImageId}`
      return {
        imageId: parsedImageId,
        row: parsedRow,
        col: parsedCol,
        baseUrl: imageSliceIdBaseUrl || '/api/g/f/p/',
        fullUrl,
        cacheKey: imageSliceId,
        useFallback: false
      }
    } else if (
      imageId !== undefined &&
      row !== undefined &&
      col !== undefined
    ) {
      // URL参数格式：通过imageId, row, col参数
      const fullUrl = `${imageIdBaseUrl || '/api/g/f/p/'}${imageId}`
      return {
        imageId,
        row,
        col,
        baseUrl: imageIdBaseUrl || '/api/g/f/p/',
        fullUrl,
        cacheKey: `${imageId}_${row}_${col}`,
        useFallback: false
      }
    } else {
      // 兼容旧格式
      const urlMatch = imageUrl?.match(/\/api\/g\/f\/p\/(\d+)/)
      const extractedImageId = urlMatch ? urlMatch[1] : 'unknown'
      return {
        imageId: extractedImageId,
        row: positionRow || 0,
        col: positionCol || 0,
        baseUrl: '/api/g/f/p/',
        fullUrl: imageUrl || '',
        cacheKey: `${extractedImageId}_${positionRow || 0}_${positionCol || 0}`,
        useFallback: false
      }
    }
  }, [
    imageSliceId,
    imageSliceIdBaseUrl,
    imageId,
    imageIdBaseUrl,
    row,
    col,
    imageUrl,
    positionRow,
    positionCol
  ])
  const [sliceImage, setSliceImage] = useState<string>(() => {
    // 初始化时检查缓存
    if (params.useFallback) {
      return ''
    }
    return sliceCache.get(params.cacheKey) || ''
  })
  const [isLoading, setIsLoading] = useState(() => {
    // 初始化时检查缓存状态
    if (params.useFallback) {
      return false
    }
    return !sliceCache.has(params.cacheKey)
  })
  const [hasError, setHasError] = useState(false)

  // 默认配置 - 图片切片参数
  const cellWidth = 28
  const cellHeight = 28
  const offsetX = 5
  const offsetY = 2
  const rowSpacing = 10
  const colSpacing = 10

  // 计算指定位置的切片坐标
  const getSliceCoordinates = useCallback((row: number, col: number) => {
    const x = offsetX + col * (cellWidth + colSpacing)
    const y = offsetY + row * (cellHeight + rowSpacing)

    return {
      x,
      y,
      width: cellWidth,
      height: cellHeight
    }
  }, [])

  // 从缓存获取或加载完整图片
  const getOrLoadImage = useCallback(
    (imageUrl: string): Promise<HTMLImageElement> => {
      return new Promise((resolve, reject) => {
        console.log('尝试加载图片:', imageUrl)

        // 检查缓存
        if (imageCache.has(imageUrl)) {
          console.log('从缓存获取图片:', imageUrl)
          const cachedImage = imageCache.get(imageUrl)!
          resolve(cachedImage)
          return
        }

        // 加载新图片
        const img = new Image()
        img.crossOrigin = 'anonymous'

        img.onload = () => {
          console.log('图片加载成功，添加到缓存:', imageUrl)
          imageCache.set(imageUrl, img)
          resolve(img)
        }

        img.onerror = (error) => {
          console.error('图片加载失败:', imageUrl, error)
          reject(new Error(`Failed to load image: ${imageUrl}`))
        }

        img.src = imageUrl
      })
    },
    []
  )

  // 从完整图片中提取指定位置的切片
  const extractSlice = useCallback(async () => {
    console.log('开始提取切片:', params.cacheKey, params.fullUrl)

    if (params.row < 0 || params.row > 4 || params.col < 0 || params.col > 4) {
      console.log('位置参数无效:', params.row, params.col)
      setHasError(true)
      setIsLoading(false)
      return
    }

    // 检查切片缓存
    if (sliceCache.has(params.cacheKey)) {
      console.log('从缓存获取切片:', params.cacheKey)
      const cachedSlice = sliceCache.get(params.cacheKey)!
      setSliceImage(cachedSlice)
      setIsLoading(false)
      setHasError(false)
      onLoad?.()
      return
    }

    // 使用动态创建的 canvas 来避免 DOM 依赖问题
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')

    if (!ctx) {
      console.error('无法创建Canvas context')
      setHasError(true)
      setIsLoading(false)
      return
    }

    try {
      console.log('开始加载图片:', params.fullUrl)
      // 加载完整图片
      const img = await getOrLoadImage(params.fullUrl)
      console.log('图片加载成功，尺寸:', img.width, 'x', img.height)

      const slice = getSliceCoordinates(params.row, params.col)
      console.log('切片坐标:', slice)

      // 设置 canvas 尺寸
      canvas.width = slice.width
      canvas.height = slice.height

      // 清空 canvas
      ctx.clearRect(0, 0, slice.width, slice.height)

      // 检查是否需要调整为正方形
      if (slice.width === slice.height) {
        // 如果切片本身就是正方形，直接绘制
        canvas.width = slice.width
        canvas.height = slice.height

        ctx.drawImage(
          img,
          slice.x,
          slice.y,
          slice.width,
          slice.height,
          0,
          0,
          slice.width,
          slice.height
        )
      } else {
        // 从大图中切出对应位置的小图
        // 先提取原始切片区域
        const sourceCanvas = document.createElement('canvas')
        const sourceCtx = sourceCanvas.getContext('2d')

        if (!sourceCtx) {
          throw new Error('无法创建源canvas context')
        }

        sourceCanvas.width = slice.width
        sourceCanvas.height = slice.height

        // 绘制原始切片
        sourceCtx.drawImage(
          img,
          slice.x,
          slice.y,
          slice.width,
          slice.height,
          0,
          0,
          slice.width,
          slice.height
        )

        // 将切片调整为正方形
        const squareSize = Math.max(slice.width, slice.height)
        canvas.width = squareSize
        canvas.height = squareSize

        // 重新清空canvas（因为尺寸改变了）
        ctx.clearRect(0, 0, squareSize, squareSize)

        // 计算居中位置
        const offsetX = (squareSize - slice.width) / 2
        const offsetY = (squareSize - slice.height) / 2

        // 绘制到正方形canvas的中心位置
        ctx.drawImage(
          sourceCanvas,
          0,
          0,
          slice.width,
          slice.height,
          offsetX,
          offsetY,
          slice.width,
          slice.height
        )
      }

      // 将切出的图片转换为 base64
      const extractedImage = canvas.toDataURL('image/png')
      console.log('切片提取成功:', params.cacheKey)

      // 缓存切片
      sliceCache.set(params.cacheKey, extractedImage)

      setSliceImage(extractedImage)
      setIsLoading(false)
      setHasError(false)
      onLoad?.()
    } catch (error) {
      console.error('切片提取失败:', error, params.fullUrl)
      setHasError(true)
      setIsLoading(false)
      onError?.()
    }
  }, [
    params.cacheKey,
    params.fullUrl,
    params.row,
    params.col,
    getSliceCoordinates,
    getOrLoadImage,
    onLoad,
    onError
  ])

  useEffect(() => {
    // 如果需要回退到普通图片显示
    if (params.useFallback) {
      setIsLoading(false)
      setHasError(false)
      return
    }

    // 检查切片缓存，如果已缓存则直接使用
    if (sliceCache.has(params.cacheKey)) {
      setSliceImage(sliceCache.get(params.cacheKey)!)
      setIsLoading(false)
      setHasError(false)
      onLoad?.()
      return
    }

    // 只有当缓存中没有时才设置加载状态
    setIsLoading(true)
    setHasError(false)

    // 确保在下一个事件循环中执行，让 DOM 完全渲染
    const timer = setTimeout(() => {
      extractSlice()
    }, 0)

    return () => {
      clearTimeout(timer)
    }
  }, [
    params.cacheKey,
    params.fullUrl,
    params.useFallback,
    extractSlice,
    onLoad
  ])

  // 计算正方形尺寸
  const squareSize = Math.max(width || cellWidth, height || cellHeight)

  // 渲染加载状态
  if (isLoading) {
    return (
      <div
        className={`flex items-center justify-center rounded bg-gray-100 ${className}`}
        style={{ width: squareSize, height: squareSize }}
      >
        <div className="text-xs text-gray-500">加载中...</div>
      </div>
    )
  }

  // 渲染错误状态
  if (hasError) {
    return (
      <div
        className={`flex items-center justify-center rounded bg-red-100 ${className}`}
        style={{ width: squareSize, height: squareSize }}
      >
        <div className="text-xs text-red-500">错误</div>
      </div>
    )
  }

  // 渲染图片
  return (
    <div
      className={`overflow-hidden rounded ${className}`}
      style={{ width: squareSize, height: squareSize }}
    >
      {params.useFallback ? (
        // 使用普通图片显示
        <img
          src={params.fullUrl}
          alt={alt}
          className="size-full object-cover"
        />
      ) : (
        // 使用切片图片显示
        <img src={sliceImage} alt={alt} className="size-full object-contain" />
      )}
    </div>
  )
})

// 碎片数据接口
export interface PieceData {
  id: number
  name: string
  alias?: string
  describe?: string
  score: number
  avatar: string
  props: string
}

// 位置数据接口
export interface PositionData {
  row: number
  col: number
  id?: string
  name?: string
  piece?: PieceData // 可选的碎片数据
}

// 批量显示组件
interface ImageSliceGridProps {
  imageId?: string // 新格式：图片ID
  imageUrl?: string // 兼容旧格式
  baseUrl?: string // 基础URL
  positions: Array<PositionData>
  className?: string
  itemClassName?: string
  showLabels?: boolean
  showPieceInfo?: boolean // 是否显示碎片信息
  onItemClick?: (position: PositionData, index: number) => void
}

export function ImageSliceGrid({
  imageId,
  imageUrl,
  baseUrl,
  positions,
  className = '',
  itemClassName = '',
  showLabels = false,
  showPieceInfo = false,
  onItemClick
}: ImageSliceGridProps) {
  // 计算网格列数，自动调整为方形布局
  const itemCount = positions.length
  const gridCols = Math.ceil(Math.sqrt(itemCount))

  return (
    <div
      className={`grid gap-3 ${className}`}
      style={{
        gridTemplateColumns: `repeat(${gridCols}, minmax(0, 1fr))`,
        width: 'fit-content',
        maxWidth: '100%'
      }}
    >
      {positions.map((position, index) => {
        const key = position.id || `${position.row}-${position.col}`
        const piece = position.piece

        // 构造props - 确保传递正方形尺寸
        const imageSize = 32 // 标准正方形尺寸
        const sliceProps = imageId
          ? {
              imageSliceId: `${imageId}_${position.row}_${position.col}`,
              baseUrl,
              alt: position.name || `图片 ${position.row}-${position.col}`,
              width: imageSize,
              height: imageSize
            }
          : {
              imageUrl: imageUrl!,
              position: { row: position.row, col: position.col },
              alt: position.name || `图片 ${position.row}-${position.col}`,
              width: imageSize,
              height: imageSize
            }

        return (
          <div
            key={key}
            className={`group relative flex flex-col items-center justify-center rounded-lg p-2 transition-all duration-200 ${itemClassName} ${
              onItemClick
                ? 'cursor-pointer hover:scale-105 hover:bg-gray-100 hover:shadow-md active:scale-95'
                : ''
            }`}
            style={{
              minWidth: '48px',
              minHeight: showLabels || showPieceInfo ? '80px' : '48px'
            }}
            onClick={() => onItemClick?.(position, index)}
          >
            {/* 图片容器 */}
            <div className="flex size-8 items-center justify-center rounded border border-gray-200 bg-white shadow-sm">
              <ImageSliceViewer {...sliceProps} />
            </div>

            {/* 标签区域 */}
            {(showLabels || showPieceInfo) && (
              <div className="mt-1 w-full space-y-1 text-center text-xs">
                {/* 位置标签 */}
                {showLabels && (
                  <div className="max-w-full truncate text-gray-600">
                    {position.name || `(${position.row},${position.col})`}
                  </div>
                )}

                {/* 碎片信息 */}
                {showPieceInfo && piece && (
                  <div className="space-y-1">
                    <div
                      className="truncate font-medium text-gray-800"
                      title={piece.name}
                    >
                      {piece.name}
                    </div>
                    {piece.alias && (
                      <div
                        className="truncate font-mono text-xs text-blue-600"
                        title={piece.alias}
                      >
                        [{piece.alias}]
                      </div>
                    )}
                    <div className="text-xs text-gray-400">{piece.score}</div>
                  </div>
                )}

                {/* 无数据提示 */}
                {showPieceInfo && !piece && (
                  <div className="text-xs text-gray-400">无数据</div>
                )}
              </div>
            )}

            {/* Hover 详情卡片 */}
            {piece && (
              <div className="pointer-events-none absolute bottom-full left-1/2 z-10 mb-2 -translate-x-1/2 opacity-0 transition-opacity duration-200 group-hover:opacity-100">
                <div className="whitespace-nowrap rounded-lg border border-gray-200 bg-white p-3 text-xs shadow-lg">
                  <div className="mb-1 font-medium text-gray-800">
                    {piece.name}
                  </div>
                  {piece.alias && (
                    <div className="mb-1 font-mono text-blue-600">
                      [{piece.alias}]
                    </div>
                  )}
                  {piece.describe && (
                    <div className="mb-1 max-w-48 whitespace-normal text-gray-600">
                      {piece.describe}
                    </div>
                  )}
                  <div className="text-gray-500">
                    位置: ({position.row}, {position.col}) | 分数: {piece.score}
                  </div>
                  <div className="absolute left-1/2 top-full -mt-1 -translate-x-1/2">
                    <div className="size-2 rotate-45 border-b border-r border-gray-200 bg-white"></div>
                  </div>
                </div>
              </div>
            )}
          </div>
        )
      })}
    </div>
  )
}

// 新增：便捷的URL生成函数
export function generateSliceUrl(
  imageSliceId: string,
  baseUrl = '/api/g/f/p/'
) {
  const parts = imageSliceId.split('_')
  if (parts.length !== 3) {
    throw new Error(
      `Invalid imageSliceId format: ${imageSliceId}. Expected format: "imageId_row_col"`
    )
  }

  const imageId = parts[0]
  return `${baseUrl}${imageId}`
}

// 新增：便捷的切片ID生成函数
export function generateSliceId(imageId: string, row: number, col: number) {
  return `${imageId}_${row}_${col}`
}

// 新增：清理缓存函数
export function clearImageCache() {
  imageCache.clear()
  sliceCache.clear()
}

export default ImageSliceViewer
